package com.ruoyi.quartz.task;

import cn.hutool.core.util.ArrayUtil;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.quartz.util.TestTable2;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import org.apache.poi.ss.usermodel.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.ruoyi.common.utils.StringUtils;
import sun.management.Agent;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 定时任务调度测试
 *
 * @author ruoyi
 */
@Component
@EnableScheduling   // 1.开启定时任务
@EnableAsync        // 2.开启多线程
public class RyTask
{

    private static final Logger logger = LoggerFactory.getLogger(RyTask.class);

    @Autowired
    private IAdminPrizeConfigService iAdminPrizeConfigService;

    @Autowired
    private LuckTask luckTask;

    @Autowired
    private IAdminUserFlowingService iAdminUserFlowingService;

    @Autowired
    private IAdminPrizeRecordService iAdminPrizeRecordService;

    @Autowired
    private IAdminUserBetRecordService iAdminUserBetRecordService;

    @Autowired
    private   IAdminWeixinUserService iAdminWeixinUserService;

    @Autowired
    private IAdminAgentInfoService iAdminAgentInfoService;

    @Autowired
    private IAdminPumpRecordService iAdminPumpRecordService;

    @Autowired
    private IAdminAgentRobotService iAdminAgentRobotService;

    @Autowired
    private IAdminUpdownBranchService iAdminUpdownBranchService;

    ExecutorService es3 = Executors.newCachedThreadPool();


    @Value("${send.url}")
    private String sendUrl;

    @Value("${send.urlOne}")
    private String sendUrlOne;


    @Value("${send.urlTwo}")
    private String sendUrlTwo;


    public void ryMultipleParams(String s, Boolean b, Long l, Double d, Integer i)
    {
        System.out.println(StringUtils.format("执行多参方法： 字符串类型{}，布尔类型{}，长整型{}，浮点型{}，整形{}", s, b, l, d, i));
    }

    public void ryParams(String params)
    {
        System.out.println("执行有参方法：" + params);
    }

    public void ryNoParams()
    {
        System.out.println("执行无参方法");
    }

    public void insertPrizeRecordThree()
    {
        logger.info("------------------------加开奖记录---------------------------");
        AdminPrizeConfig stateInfo = iAdminPrizeConfigService.selectAdminPrizeConfigByKey("state");
        if (stateInfo==null) {
            AdminPrizeConfig adminPrizeConfig = new AdminPrizeConfig();
            adminPrizeConfig.setConfigName("开奖开关");
            adminPrizeConfig.setConfigKey("state");
            adminPrizeConfig.setConfigValue("1");
            adminPrizeConfig.setRemark("开奖开关设置:1:代表开启开奖  2：关闭开奖");
            adminPrizeConfig.setCreateTime(DateUtils.getNowDate());
            iAdminPrizeConfigService.insertAdminPrizeConfig(adminPrizeConfig);
        }
        AdminPrizeConfig sealingTime = iAdminPrizeConfigService.selectAdminPrizeConfigByKey("sealingTime");
        if (sealingTime==null) {
            AdminPrizeConfig adminPrizeConfig = new AdminPrizeConfig();
            adminPrizeConfig.setConfigName("封盘时间");
            adminPrizeConfig.setConfigKey("sealingTime");
            adminPrizeConfig.setConfigValue("1");
            adminPrizeConfig.setRemark("封盘时间");
            adminPrizeConfig.setCreateTime(DateUtils.getNowDate());
            iAdminPrizeConfigService.insertAdminPrizeConfig(adminPrizeConfig);
        }
        AdminPrizeConfig oddsInfo = iAdminPrizeConfigService.selectAdminPrizeConfigByKey("odds");
        if (oddsInfo==null) {
            AdminPrizeConfig adminPrizeConfig = new AdminPrizeConfig();
            adminPrizeConfig.setConfigName("赔率");
            adminPrizeConfig.setConfigKey("odds");
            adminPrizeConfig.setConfigValue("1");
            adminPrizeConfig.setRemark("赔率");
            adminPrizeConfig.setCreateTime(DateUtils.getNowDate());
            iAdminPrizeConfigService.insertAdminPrizeConfig(adminPrizeConfig);
        }
        AdminPrizeConfig periodsInfo = iAdminPrizeConfigService.selectAdminPrizeConfigByKey("periods");
        if (periodsInfo==null) {
            AdminPrizeConfig adminPrizeConfig = new AdminPrizeConfig();
            adminPrizeConfig.setConfigName("每次生成期数");
            adminPrizeConfig.setConfigKey("periods");
            adminPrizeConfig.setConfigValue("10");
            adminPrizeConfig.setRemark("开奖资源池内剩余的期数");
            adminPrizeConfig.setCreateTime(DateUtils.getNowDate());
            iAdminPrizeConfigService.insertAdminPrizeConfig(adminPrizeConfig);
        }
        AdminPrizeConfig intervalInfo = iAdminPrizeConfigService.selectAdminPrizeConfigByKey("interval");
        if (intervalInfo==null) {
            AdminPrizeConfig adminPrizeConfig = new AdminPrizeConfig();
            adminPrizeConfig.setConfigName("开奖时间间隔");
            adminPrizeConfig.setConfigKey("interval");
            adminPrizeConfig.setConfigValue("5");
            adminPrizeConfig.setRemark("开奖时间间隔：单位为分");
            adminPrizeConfig.setCreateTime(DateUtils.getNowDate());
            iAdminPrizeConfigService.insertAdminPrizeConfig(adminPrizeConfig);
        }
        AdminPrizeConfig minUpPrice = iAdminPrizeConfigService.selectAdminPrizeConfigByKey("minUpPrice");
        if (minUpPrice==null) {
            AdminPrizeConfig adminPrizeConfig = new AdminPrizeConfig();
            adminPrizeConfig.setConfigName("最小上分数");
            adminPrizeConfig.setConfigKey("minUpPrice");
            adminPrizeConfig.setConfigValue("100");
            adminPrizeConfig.setRemark("最小上分数");
            adminPrizeConfig.setCreateTime(DateUtils.getNowDate());
            iAdminPrizeConfigService.insertAdminPrizeConfig(adminPrizeConfig);
        }
        AdminPrizeConfig maxUpPrice = iAdminPrizeConfigService.selectAdminPrizeConfigByKey("maxUpPrice");
        if (maxUpPrice==null) {
            AdminPrizeConfig adminPrizeConfig = new AdminPrizeConfig();
            adminPrizeConfig.setConfigName("最大上分数");
            adminPrizeConfig.setConfigKey("maxUpPrice");
            adminPrizeConfig.setConfigValue("20000");
            adminPrizeConfig.setRemark("最大上分数");
            adminPrizeConfig.setCreateTime(DateUtils.getNowDate());
            iAdminPrizeConfigService.insertAdminPrizeConfig(adminPrizeConfig);
        }
        stateInfo = iAdminPrizeConfigService.selectAdminPrizeConfigByKey("state");
        periodsInfo = iAdminPrizeConfigService.selectAdminPrizeConfigByKey("periods");
        intervalInfo = iAdminPrizeConfigService.selectAdminPrizeConfigByKey("interval");
        if (stateInfo.getConfigValue().equals("2")) {
            return;
        }
        AdminPrizeRecord selectPrizeRecord=new AdminPrizeRecord();
        selectPrizeRecord.setState(1);
        List<AdminPrizeRecord> adminPrizeRecords = iAdminPrizeRecordService.selectAdminPrizeRecordListTwo(selectPrizeRecord);
        Integer insertRecord=Integer.valueOf(periodsInfo.getConfigValue()).intValue()-adminPrizeRecords.size();
        if (insertRecord>0) {
            for (int i=0;i<insertRecord;i++) {
                AdminPrizeRecord adminPrizeRecord = iAdminPrizeRecordService.selectAdminPrizeRecordByMaxPeriod();
                AdminPrizeRecord insertPrizeRecord = new AdminPrizeRecord();
                if (adminPrizeRecord!=null) {
    //                insertPrizeRecord.setPrizeTime(DateUtils.addMilliseconds(adminPrizeRecord.getPrizeTime(),Integer.valueOf(intervalInfo.getConfigValue()).intValue()));
                    insertPrizeRecord.setPeriod(adminPrizeRecord.getPeriod()+1);
                }else {
    //                insertPrizeRecord.setPrizeTime(DateUtils.getNowDate());
                    insertPrizeRecord.setPeriod(200000L);
                }
                insertPrizeRecord.setLotteryNumber(getRandomNum());
                insertPrizeRecord.setCreateTime(DateUtils.getNowDate());
                insertPrizeRecord.setState(1);
                iAdminPrizeRecordService.insertAdminPrizeRecord(insertPrizeRecord);
            }
        }
    }

    @Scheduled(cron="2,32 2,3,7,8,12,13,17,18,22,23,27,28,32,33,37,38,42,43,47,48,52,53,57,58 * * * ?")
    public  void drawThree() {
        logger.info("------------------------正常开奖流程---------------------------");
                Map<String, Object> stringObjectMap = iAdminPrizeRecordService.selectAdminPrizeRecordCount();
                AdminPrizeConfig stateInfo = iAdminPrizeConfigService.selectAdminPrizeConfigByKey("state");
                AdminPrizeConfig intervalInfo = iAdminPrizeConfigService.selectAdminPrizeConfigByKey("interval");
                if (stateInfo.getConfigValue().equals("2")) {
                    return;
                }
                //        iAdminPrizeRecordService.updatePrizeState();
                if (Integer.valueOf(stringObjectMap.get("count").toString()).intValue() == 0) {
                    return;
                }
                //有修改时间，没开奖的记录
                AdminPrizeRecord prizeRecord = new AdminPrizeRecord();
                AdminPrizeRecord notPrizeRecord = iAdminPrizeRecordService.selectAdminPrizeRecordByPrizeTime();
                //初始化未开过奖时，会有为空的情况，如果为空，将期数最小的数据找出
                if (notPrizeRecord == null) {
                    insertPrizeRecordThree();
                    notPrizeRecord = iAdminPrizeRecordService.getMinPrizeInfoByPeriod();
                    //如果这里还是为空，可能是另一个调度还未预先生成号码，先返回
                    if (notPrizeRecord == null) {
                        return;
                    }
                    prizeRecord.setPrizeTime(DateUtils.getNowDate());
                    prizeRecord.setRecordId(notPrizeRecord.getRecordId());
                    prizeRecord.setState(1);
                    iAdminPrizeRecordService.updateAdminPrizeRecord(prizeRecord);
                    logger.info(prizeRecord.toString());
                } else {
                    //            AdminPrizeConfig oddsInfo = iAdminPrizeConfigService.selectAdminPrizeConfigByKey("odds");
                    AdminPrizeConfig sealingTime = iAdminPrizeConfigService.selectAdminPrizeConfigByKey("sealingTime");
                    int sealingTimeValue = Integer.valueOf(sealingTime.getConfigValue()).intValue();
                    AdminPrizeRecord sealingPrizeRecord = iAdminPrizeRecordService.selectAdminPrizeRecordById(notPrizeRecord.getRecordId());
                    //封盘时间
                    Date sealingDate = DateUtils.addMinutes(notPrizeRecord.getPrizeTime(), -sealingTimeValue);
                    //提前30秒封盘时间
                    Date advanceDate = DateUtils.addSeconds(sealingDate, -30);
                    //封盘前给代理发消息
                    if (DateUtils.getNowDate().getTime() >= advanceDate.getTime() && sealingPrizeRecord.getSealingState() == 0) {
                        //修改已提前发过消息
                        AdminPrizeRecord updatePrizeRecord = new AdminPrizeRecord();
                        updatePrizeRecord.setRecordId(notPrizeRecord.getRecordId());
                        updatePrizeRecord.setSealingState(1);
                        iAdminPrizeRecordService.updateAdminPrizeRecord(updatePrizeRecord);
                        AdminAgentInfo adminAgentInfo = new AdminAgentInfo();
                        String sendMsg = "30秒后封盘!";
                        List<AdminAgentInfo> adminAgentInfos = iAdminAgentInfoService.selectAdminAgentInfoList(adminAgentInfo);
                        if (adminAgentInfos.size() > 0) {
                            for (AdminAgentInfo agentInfo : adminAgentInfos) {
                                if (agentInfo.getAgentState() == 1) {
                                    String room = agentInfo.getRoom();
                                    HttpUtils.sendPost(sendUrl, "sendMsg=" + sendMsg + "&room=" + room);
                                }
                            }
                        }
                        insertPrizeRecordThree();
                        System.gc();
                    }
                    //            AdminAgentInfo adminAgentInfo = new AdminAgentInfo();
                    //            List<AdminAgentInfo> adminAgentInfos = iAdminAgentInfoService.selectAdminAgentInfoList(adminAgentInfo);
                    //            List<AdminUserBetRecord> adminUserBetRecordList = iAdminUserBetRecordService.selectAdminUserBetRecordByPeriod(notPrizeRecord.getPeriod());
                    //封盘给代理发送封盘消息
                    if (DateUtils.getNowDate().getTime() >= sealingDate.getTime() && sealingPrizeRecord.getSealingState() == 1) {
                        AdminAgentInfo adminAgentInfo = new AdminAgentInfo();
                        List<AdminAgentInfo> adminAgentInfos = iAdminAgentInfoService.selectAdminAgentInfoList(adminAgentInfo);
                        if (adminAgentInfos.size() > 0) {
                            for (AdminAgentInfo agentInfo : adminAgentInfos) {
                                if (agentInfo.getAgentState() == 1 && agentInfo.getAgentType() == 1) {
                                    String room = agentInfo.getRoom();
                                    AdminUserBetRecord betRecord = new AdminUserBetRecord();
                                    betRecord.setRoom(room);
                                    betRecord.setPeriod(notPrizeRecord.getPeriod());
                                    List<AdminUserBetRecord> adminUserBetRecords = iAdminUserBetRecordService.selectAdminUserBetRecordByPeriodAndRoomInfo(betRecord);
                                    //该代理投注的所有金额
                                    Double sumPrice = iAdminUserBetRecordService.selectAllSumPriceByPeriodAndRoom(betRecord);
                                    List<HashMap<String, Object>> userBetRecords = iAdminUserBetRecordService.selectAdminUserBetRecordGroupByPayNum(betRecord);
                                    double pumpPrice = 0;
                                    double remainPrice = 0;
                                    if (sumPrice != null) {
                                        //抽水金额多位小数
                                        Double moreV = sumPrice * new Double(agentInfo.getOdds().toString());
                                        //代理抽水金额
                                        pumpPrice = new Double(String.format("%.2f", moreV));
                                        //                            pumpPrice = sumPrice * new Double(agentInfo.getOdds().toString());
                                        //剩余金额
                                        remainPrice = sumPrice - pumpPrice;
                                    } else {
                                        sumPrice = new Double(0);
                                    }
                                    String sendMsg = "开奖期数：" + notPrizeRecord.getPeriod() + "\n";
                                    //                        sendMsg = sendMsg + "总榜：(" + notPrizeRecord.getJackpotPrice() + ")\n";
                                    Map<String, String> userMap = new LinkedHashMap<>();
                                    for (AdminUserBetRecord adminUserBetRecord : adminUserBetRecords) {
                                        if (userMap.get(adminUserBetRecord.getWexinId()) == null) {
                                            userMap.put(adminUserBetRecord.getWexinId(), adminUserBetRecord.getCommand());
                                        } else {
                                            userMap.put(adminUserBetRecord.getWexinId(), userMap.get(adminUserBetRecord.getWexinId()) + "，" + adminUserBetRecord.getCommand());
                                        }
                                    }
                                    for (String key : userMap.keySet()) {
                                        AdminWeixinUser adminWeixinUser1 = new AdminWeixinUser();
                                        adminWeixinUser1.setRoom(room);
                                        adminWeixinUser1.setWexinId(key);
                                        AdminWeixinUser adminWeixinUser = iAdminWeixinUserService.selectAdminWeixinUserByWeChatIdAndRoom(adminWeixinUser1);
                                        sendMsg = sendMsg + "(" + adminWeixinUser.getWexinName() + ")  " + "\"" + userMap.get(key) + "\"" + "\n";
                                        System.out.println(key);
                                    }
                                    sendMsg = sendMsg + "----------------------" + "\n";
                                    for (HashMap<String, Object> userBetRecord : userBetRecords) {
                                        String num = userBetRecord.get("num").toString();
                                        String price = userBetRecord.get("price").toString();
                                        sendMsg = sendMsg + num + "球：" + price + "\n";
                                    }
                                    sendMsg = sendMsg + "总和:" + sumPrice + "  抽水:" + pumpPrice + " 剩余:" + String.format("%.2f", remainPrice) + "\n";
                                    sendMsg = sendMsg + "----------------------" + "\n";
                                    sendMsg = sendMsg + "以核对列表为效" + "\n";
                                    sendMsg = sendMsg + "不在列表都无效" + "\n";
                                    AdminPrizeRecord updatePrizeRecord = new AdminPrizeRecord();
                                    updatePrizeRecord.setRecordId(notPrizeRecord.getRecordId());
                                    updatePrizeRecord.setSealingState(2);
                                    iAdminPrizeRecordService.updateAdminPrizeRecord(updatePrizeRecord);
                                    HttpUtils.sendPost(sendUrl, "sendMsg=" + "停止" + "&room=" + room);
                                    HttpUtils.sendPost(sendUrl, "sendMsg=" + sendMsg + "&room=" + room);
                                } else if (agentInfo.getAgentState() == 1 && agentInfo.getAgentType() == 2) {

                                    String room = agentInfo.getRoom();
                                    AdminUserBetRecord betRecord = new AdminUserBetRecord();
                                    betRecord.setRoom(room);
                                    betRecord.setPeriod(notPrizeRecord.getPeriod());
                                    List<AdminUserBetRecord> adminUserBetRecords = iAdminUserBetRecordService.selectAdminUserBetRecordByPeriodAndRoomInfo(betRecord);
                                    //该代理投注的所有金额
                                    Double sumPrice = iAdminUserBetRecordService.selectAllSumPriceByPeriodAndRoom(betRecord);
                                    List<HashMap<String, Object>> userBetRecords = iAdminUserBetRecordService.selectAdminUserBetRecordGroupByPayNum(betRecord);
                                    double pumpPrice = 0;
                                    double remainPrice = 0;
                                    if (sumPrice != null) {
                                        //抽水金额多位小数
                                        Double moreV = sumPrice * new Double(agentInfo.getOdds().toString());
                                        //代理抽水金额
                                        pumpPrice = new Double(String.format("%.2f", moreV));
                                        //                            pumpPrice = sumPrice * new Double(agentInfo.getOdds().toString());
                                        //剩余金额
                                        remainPrice = sumPrice - pumpPrice;
                                    } else {
                                        sumPrice = new Double(0);
                                    }
                                    String sendMsg = "开奖期数：" + notPrizeRecord.getPeriod() + "\n";

                                    Map<String, String> userMap = new LinkedHashMap<>();
                                    for (AdminUserBetRecord adminUserBetRecord : adminUserBetRecords) {
                                        if (userMap.get(adminUserBetRecord.getWexinId()) == null) {
                                            userMap.put(adminUserBetRecord.getWexinId(), adminUserBetRecord.getCommand());
                                        } else {
                                            userMap.put(adminUserBetRecord.getWexinId(), userMap.get(adminUserBetRecord.getWexinId()) + "，" + adminUserBetRecord.getCommand());
                                        }
                                    }
                                    for (String key : userMap.keySet()) {
                                        AdminWeixinUser adminWeixinUser1 = new AdminWeixinUser();
                                        adminWeixinUser1.setRoom(room);
                                        adminWeixinUser1.setWexinId(key);
                                        AdminWeixinUser adminWeixinUser = iAdminWeixinUserService.selectAdminWeixinUserByWeChatIdAndRoom(adminWeixinUser1);
                                        sendMsg = sendMsg + "(" + adminWeixinUser.getWexinName() + ")  " + "\"" + userMap.get(key) + "\"" + "\n";
                                        System.out.println(key);
                                    }
                                    sendMsg = sendMsg + "----------------------" + "\n";
                                    sendMsg = sendMsg + "总和:" + sumPrice + "\n";
                                    sendMsg = sendMsg + "----------------------" + "\n";
                                    sendMsg = sendMsg + "以核对列表为效" + "\n";
                                    sendMsg = sendMsg + "不在列表都无效" + "\n";
                                    sendMsg = sendMsg.replaceAll("\\+", "%2B");
                                    AdminPrizeRecord updatePrizeRecord = new AdminPrizeRecord();
                                    updatePrizeRecord.setRecordId(notPrizeRecord.getRecordId());
                                    updatePrizeRecord.setSealingState(2);
                                    iAdminPrizeRecordService.updateAdminPrizeRecord(updatePrizeRecord);
                                    HttpUtils.sendPost(sendUrl, "sendMsg=" + "停止" + "&room=" + room);
                                    HttpUtils.sendPost(sendUrl, "sendMsg=" + sendMsg + "&room=" + room);
                                }
                            }
                        }

                    }
                    //正常开奖流程
                    if (notPrizeRecord.getPrizeTime().getTime() < DateUtils.getNowDate().getTime()) {

                        String sendMsg = "开奖期数：" + notPrizeRecord.getPeriod() + "\n";
                        prizeRecord.setPrizeTime(DateUtils.getNowDate());
                        prizeRecord.setRecordId(notPrizeRecord.getRecordId());
                        prizeRecord.setState(2);
                        iAdminPrizeRecordService.updateAdminPrizeRecord(prizeRecord);
                        BigDecimal setRemainingPrice = notPrizeRecord.getRemainingPrice();
                        //分发奖池金额
                        //                int[] array = getArray(notPrizeRecord.getLotteryNumber());
                        //                int[] onArray = Arrays.copyOfRange(array, 0, 5);
                        AdminPrizeRecord selectHistoryRecord = new AdminPrizeRecord();
                        List<AdminPrizeRecord> adminPrizeRecords = iAdminPrizeRecordService.selectAdminPrizeRecordListToAgentFifty(selectHistoryRecord);

                        //发图片
                        sendImagesMessage(adminPrizeRecords);

                        //发开奖记录
                        sendAllMessageToRoom(notPrizeRecord);

                        HashMap hashMap = new HashMap();
                        String[] strings = notPrizeRecord.getLotteryNumber().split(",");
                        Integer num = Integer.valueOf(strings[7]) % 4;
                        num = num == 0 ? 4 : num;
                        hashMap.put("num", num);
                        hashMap.put("period", notPrizeRecord.getPeriod());
                        hashMap.put("time", DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", notPrizeRecord.getPrizeTime()));

                        luckTask.sendImgOne(hashMap, strings);

                        //发图片
                        luckTask.sendImagesMessage(adminPrizeRecords);


                        //发开奖记录
                        luckTask.sendAllMessageToRoom(notPrizeRecord);

                        luckTask.sendTwoMessageToRoom(notPrizeRecord.getPeriod() + 1);


                        AdminPrizeRecord prizeInfo = iAdminPrizeRecordService.getMinPrizeInfoByPeriod();
                        AdminPrizeRecord adminPrizeRecord = new AdminPrizeRecord();
                        //        AdminPrizeRecord currentPrizeInfo = iAdminPrizeRecordService.getCurrentPrizeInfo();

                        Date prizeTime = prizeRecord.getPrizeTime();
                        Date date = DateUtils.addMinutes(prizeTime, Integer.valueOf(intervalInfo.getConfigValue()).intValue());
                        if (date.getTime() < DateUtils.getNowDate().getTime()) {
                            adminPrizeRecord.setPrizeTime(DateUtils.getNowDate());
                        } else {
                            int min = Integer.valueOf(intervalInfo.getConfigValue()).intValue();
                            Date prizeDate = DateUtils.addMinutes(prizeRecord.getPrizeTime(), min);
                            adminPrizeRecord.setPrizeTime(prizeDate);
                        }
                        adminPrizeRecord.setRecordId(prizeInfo.getRecordId());
                        logger.info(adminPrizeRecord.toString());
                        iAdminPrizeRecordService.updateAdminPrizeRecord(adminPrizeRecord);
                        //发送开始下注
                        try {
                            Thread.sleep(1000L);
                            luckTask.sendToStartToRoom(notPrizeRecord.getPeriod() + 1);
                            sendToStartToRoom();

                            sendBetRecord();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        return;
                    }
                }

    }

    public  void sendBetRecord(){
        try {


                    AdminPrizeRecord notPrizeRecord = iAdminPrizeRecordService.selectAdminPrizeRecordByPrizeTime();
                    AdminPrizeConfig intervalInfo = iAdminPrizeConfigService.selectAdminPrizeConfigByKey("interval");
                    AdminPrizeConfig sealingTime = iAdminPrizeConfigService.selectAdminPrizeConfigByKey("sealingTime");
                    AdminPrizeConfig minUpPrice = iAdminPrizeConfigService.selectAdminPrizeConfigByKey("minUpPrice");
                    AdminPrizeConfig maxUpPrice = iAdminPrizeConfigService.selectAdminPrizeConfigByKey("maxUpPrice");
                    int sealingTimeValue = Integer.valueOf(sealingTime.getConfigValue()).intValue();
                    int intValue = Integer.valueOf(intervalInfo.getConfigValue()).intValue();
                    int minUpPriceValue = Integer.valueOf(minUpPrice.getConfigValue()).intValue();
                    int maxUpPriceValue = Integer.valueOf(maxUpPrice.getConfigValue()).intValue();

                    if (notPrizeRecord==null || notPrizeRecord.getIsRobot()==1) {
                        return;
                    }
                    Long period = notPrizeRecord.getPeriod();
                    //大于开始时间 小于封盘时间
                    Date sealingDate = DateUtils.addMinutes(notPrizeRecord.getPrizeTime(), -sealingTimeValue);
                    Date intValueDate = DateUtils.addMinutes(notPrizeRecord.getPrizeTime(), -intValue);
                    if (DateUtils.getNowDate().getTime() > intValueDate.getTime() && DateUtils.getNowDate().getTime() < sealingDate.getTime()) {
                        AdminAgentInfo adminAgentInfo = new AdminAgentInfo();
                        //用户统计金额
                        Map<String, BigDecimal> userPrice = new LinkedHashMap<>();
                        Map<String, String> downBranch = new LinkedHashMap<>();
                        List<AdminAgentInfo> adminAgentInfos = iAdminAgentInfoService.selectAdminAgentInfoList(adminAgentInfo);
                        if (adminAgentInfos.size() > 0) {

                            ArrayList<AdminWeixinUser> list = new ArrayList();
                            ArrayList<AdminWeixinUser> list1 = new ArrayList();
                            for (AdminAgentInfo agentInfo:adminAgentInfos) {
                                if (agentInfo.getAgentState()==1 && agentInfo.getAgentType()==1) {
                                    AdminAgentRobot adminAgentRobot = new AdminAgentRobot();
                                    adminAgentRobot.setRoom(agentInfo.getRoom());
                                    List<AdminAgentRobot> adminAgentRobots = iAdminAgentRobotService.selectAdminAgentRobotList(adminAgentRobot);
                                    if (adminAgentRobots.size() > 0) {

                                        for (AdminAgentRobot agentRobot : adminAgentRobots) {
                                            SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
                                            Date dayTimeStart = null;
                                            Date dayTimeEnd = null;
                                            boolean timeBool = false;
                                            try {
                                                dayTimeStart = df.parse(agentRobot.getBeginTime());
                                                dayTimeEnd = df.parse(agentRobot.getEndTime());
                                                timeBool = DateUtils.timeCalendar(dayTimeStart, dayTimeEnd);
                                            } catch (ParseException e) {
                                                e.printStackTrace();
                                                continue;
                                            }
                                            //若时间在这范围之内就执行
                                            if (timeBool) {
                                                //若没有投注记录就新增投注记录
                                                String room = agentRobot.getRoom();
                                                String wexinId = agentRobot.getWexinId();
                                                String wexinName = agentRobot.getWexinName();
                                                //最大余额
                                                Long maxSum = agentRobot.getMaxSum();

                                                AdminUserBetRecord adminUserBetRecord = new AdminUserBetRecord();
                                                adminUserBetRecord.setWexinId(wexinId);
                                                adminUserBetRecord.setRoom(room);
                                                adminUserBetRecord.setPeriod(period);
                                                //查询用户信息
                                                AdminWeixinUser wexinUser1 = new AdminWeixinUser();
                                                wexinUser1.setRoom(room);
                                                wexinUser1.setWexinId(wexinId);

                                                AdminWeixinUser wexinUserInfo = iAdminWeixinUserService.selectAdminWeixinUserByWeChatIdAndRoom(wexinUser1);
                                                if (userPrice.get(wexinId) == null) {
                                                    userPrice.put(wexinId, wexinUserInfo.getPrice());
                                                }
                                                //查看该机器人是否有待审核的下分记录
                                                AdminUpdownBranch adminUpdownBranchDown = new AdminUpdownBranch();
                                                adminUpdownBranchDown.setWexinId(wexinId);
                                                adminUpdownBranchDown.setRoom(room);
                                                adminUpdownBranchDown.setBranchType(2);
                                                adminUpdownBranchDown.setAuditStatus(0);
                                                AdminUpdownBranch updownBranchInfoDown = iAdminUpdownBranchService.selectAdminUpdownBranchByWeixinIdAndRoom(adminUpdownBranchDown);
                                                //下注前如果该机器人的金额大于机器人的最大余额，新增下分记录
                                                if (updownBranchInfoDown == null && wexinUserInfo.getPrice().compareTo(new BigDecimal(maxSum)) > 0) {
                                                    String msg = "下分" + wexinUserInfo.getPrice();
                                                    try {
                                                        String finalSendMsg = msg;
                                                        new Thread(new Runnable() {
                                                            @Override
                                                            public void run() {
                                                                HttpUtils.sendPost(sendUrlOne, "sendMsg=" + finalSendMsg + "&room=" + room + "&wexinId=" + wexinId);
                                                            }
                                                        }).start();
                                                        if (downBranch.get(wexinId) == null) {
                                                            downBranch.put(wexinId, "1");
                                                        }
                                                    } catch (Exception e) {
                                                        e.printStackTrace();
                                                    }
                                                }
                                                AdminUpdownBranch adminUpdownBranchDown2 = new AdminUpdownBranch();
                                                adminUpdownBranchDown2.setWexinId(wexinId);
                                                adminUpdownBranchDown2.setRoom(room);
                                                adminUpdownBranchDown2.setBranchType(2);
                                                adminUpdownBranchDown2.setAuditStatus(0);
                                                AdminUpdownBranch updownBranchInfoDown2 = iAdminUpdownBranchService.selectAdminUpdownBranchByWeixinIdAndRoom(adminUpdownBranchDown2);
                                                Double aDouble = iAdminUserBetRecordService.selectSumPriceByPeriodAndRoomAndWexinId(adminUserBetRecord);
                                                //等于零说明此机器人没投过注
                                                if (aDouble.intValue() == 0) {
                                                    int betNum = getRandomStartToEnd(agentRobot.getMinBet().intValue(), agentRobot.getMaxBet().intValue());

                                                    //查看该机器人投注几注,大于零时就发起投注，和没有待审核的下分记录投注
                                                    if (betNum > 0 && updownBranchInfoDown2 == null && downBranch.get(wexinId) == null) {
                                                        for (int i = 0; i < betNum; i++) {
                                                            //获取随机1-8球
                                                            Integer randomStartToEnd = getRandomStartToEnd(1, 8);
                                                            //查询用户信息
                                                            AdminWeixinUser adminWeixinUser1 = new AdminWeixinUser();
                                                            adminWeixinUser1.setRoom(room);
                                                            adminWeixinUser1.setWexinId(wexinId);
                                                            AdminWeixinUser userInfo = iAdminWeixinUserService.selectAdminWeixinUserByWeChatIdAndRoom(adminWeixinUser1);
                                                            //用户金额
                                                            BigDecimal price = userInfo.getPrice();
                                                            Long userId = userInfo.getId();
                                                            //投注金额
                                                            Integer betPrice = mockFloatBetween2(new Float(agentRobot.getMinPrice().toString()), new Float(agentRobot.getMaxPrice().toString()), price);
                                                            userPrice.put(wexinId, userPrice.get(wexinId).subtract(new BigDecimal(betPrice)));
                                                            if (betPrice != 0 && userPrice.get(wexinId).compareTo(new BigDecimal(0)) > 0) {
                                                                String msg = randomStartToEnd + "球" + betPrice;
                                                                AdminWeixinUser adminWeixinUser = new AdminWeixinUser();
                                                                adminWeixinUser.setRoom(room);
                                                                adminWeixinUser.setWexinId(wexinId);
                                                                adminWeixinUser.setSendMsg(msg);
                                                                list.add(adminWeixinUser);
                                                            } else {
                                                                //查看该机器人是否有待审核的上分记录
                                                                AdminUpdownBranch adminUpdownBranch = new AdminUpdownBranch();
                                                                adminUpdownBranch.setWexinId(wexinId);
                                                                adminUpdownBranch.setRoom(room);
                                                                adminUpdownBranch.setBranchType(1);
                                                                adminUpdownBranch.setAuditStatus(0);
                                                                AdminUpdownBranch updownBranchInfo = iAdminUpdownBranchService.selectAdminUpdownBranchByWeixinIdAndRoom(adminUpdownBranch);
                                                                if (updownBranchInfo == null) {
                                                                    Integer upPrice = compareFloatBetween2(new Float(minUpPriceValue), new Float(maxUpPriceValue));
                                                                    String msg = "上分" + upPrice;
                                                                    AdminWeixinUser adminWeixinUser = new AdminWeixinUser();
                                                                    adminWeixinUser.setRoom(room);
                                                                    adminWeixinUser.setWexinId(wexinId);
                                                                    adminWeixinUser.setSendMsg(msg);
                                                                    new Thread(new Runnable() {
                                                                        @Override
                                                                        public void run() {
                                                                            HttpUtils.sendPost(sendUrlOne, "sendMsg=" + msg + "&room=" + room + "&wexinId=" + wexinId);
                                                                        }
                                                                    }).start();
                                                                }
                                                                break;
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }

                                    }
                                } else if (agentInfo.getAgentType()==2 && agentInfo.getAgentState()==1) {
                                    AdminAgentRobot adminAgentRobot = new AdminAgentRobot();
                                    adminAgentRobot.setRoom(agentInfo.getRoom());
                                    List<AdminAgentRobot> adminAgentRobots = iAdminAgentRobotService.selectAdminAgentRobotList(adminAgentRobot);
                                    if (adminAgentRobots.size() > 0) {

                                        for (AdminAgentRobot agentRobot : adminAgentRobots) {
                                            SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
                                            Date dayTimeStart = null;
                                            Date dayTimeEnd = null;
                                            boolean timeBool = false;
                                            try {
                                                dayTimeStart = df.parse(agentRobot.getBeginTime());
                                                dayTimeEnd = df.parse(agentRobot.getEndTime());
                                                timeBool = DateUtils.timeCalendar(dayTimeStart, dayTimeEnd);
                                            } catch (ParseException e) {
                                                e.printStackTrace();
                                                continue;
                                            }
                                            //若时间在这范围之内就执行
                                            if (timeBool) {
                                                //若没有投注记录就新增投注记录
                                                String room = agentRobot.getRoom();
                                                String wexinId = agentRobot.getWexinId();
                                                String wexinName = agentRobot.getWexinName();
                                                //最大余额
                                                Long maxSum = agentRobot.getMaxSum();

                                                AdminUserBetRecord adminUserBetRecord = new AdminUserBetRecord();
                                                adminUserBetRecord.setWexinId(wexinId);
                                                adminUserBetRecord.setRoom(room);
                                                adminUserBetRecord.setPeriod(notPrizeRecord.getPeriod());
                                                //查询用户信息
                                                AdminWeixinUser wexinUser1 = new AdminWeixinUser();
                                                wexinUser1.setRoom(room);
                                                wexinUser1.setWexinId(wexinId);

                                                AdminWeixinUser wexinUserInfo = iAdminWeixinUserService.selectAdminWeixinUserByWeChatIdAndRoom(wexinUser1);
                                                if (userPrice.get(wexinId) == null) {
                                                    userPrice.put(wexinId, wexinUserInfo.getPrice());
                                                }
                                                //查看该机器人是否有待审核的下分记录
                                                AdminUpdownBranch adminUpdownBranchDown = new AdminUpdownBranch();
                                                adminUpdownBranchDown.setWexinId(wexinId);
                                                adminUpdownBranchDown.setRoom(room);
                                                adminUpdownBranchDown.setBranchType(2);
                                                adminUpdownBranchDown.setAuditStatus(0);
                                                AdminUpdownBranch updownBranchInfoDown = iAdminUpdownBranchService.selectAdminUpdownBranchByWeixinIdAndRoom(adminUpdownBranchDown);
                                                //下注前如果该机器人的金额大于机器人的最大余额，新增下分记录
                                                if (updownBranchInfoDown == null && wexinUserInfo.getPrice().compareTo(new BigDecimal(maxSum)) > 0) {
                                                    String msg = "下分" + wexinUserInfo.getPrice();
                                                    try {
                                                        String finalSendMsg = msg;
                                                        new Thread(new Runnable() {
                                                            @Override
                                                            public void run() {
                                                                HttpUtils.sendPost(sendUrlTwo, "sendMsg=" + finalSendMsg + "&room=" + room + "&wexinId=" + wexinId);
                                                            }
                                                        }).start();
                                                        if (downBranch.get(wexinId) == null) {
                                                            downBranch.put(wexinId, "1");
                                                        }
                                                    } catch (Exception e) {
                                                        e.printStackTrace();
                                                    }
                                                }

                                                AdminUpdownBranch adminUpdownBranchDown2 = new AdminUpdownBranch();
                                                adminUpdownBranchDown2.setWexinId(wexinId);
                                                adminUpdownBranchDown2.setRoom(room);
                                                adminUpdownBranchDown2.setBranchType(2);
                                                adminUpdownBranchDown2.setAuditStatus(0);
                                                AdminUpdownBranch updownBranchInfoDown2 = iAdminUpdownBranchService.selectAdminUpdownBranchByWeixinIdAndRoom(adminUpdownBranchDown2);
                                                Double aDouble = iAdminUserBetRecordService.selectSumPriceByPeriodAndRoomAndWexinId(adminUserBetRecord);
                                                //等于零说明此机器人没投过注
                                                if (aDouble.intValue() == 0) {
                                                    int betNum = getRandomStartToEnd(agentRobot.getMinBet().intValue(), agentRobot.getMaxBet().intValue());

                                                    //查看该机器人投注几注,大于零时就发起投注，和没有待审核的下分记录投注
                                                    if (betNum > 0 && updownBranchInfoDown2 == null && downBranch.get(wexinId) == null) {
                                                        for (int i = 0; i < betNum; i++) {
                                                            //获取随机1-8球
                                                            List<String> command = luckTask.getCommand();
                                                            Integer randomStartToEnd = getRandomStartToEnd(1, command.size()-1);
                                                            //查询用户信息
                                                            AdminWeixinUser adminWeixinUser1 = new AdminWeixinUser();
                                                            adminWeixinUser1.setRoom(room);
                                                            adminWeixinUser1.setWexinId(wexinId);
                                                            AdminWeixinUser userInfo = iAdminWeixinUserService.selectAdminWeixinUserByWeChatIdAndRoom(adminWeixinUser1);
                                                            //用户金额
                                                            BigDecimal price = userInfo.getPrice();
                                                            Long userId = userInfo.getId();
                                                            //投注金额
                                                            Integer betPrice = mockFloatBetween2(new Float(agentRobot.getMinPrice().toString()), new Float(agentRobot.getMaxPrice().toString()), price);
                                                            userPrice.put(wexinId, userPrice.get(wexinId).subtract(new BigDecimal(betPrice)));
                                                            if (betPrice != 0 && userPrice.get(wexinId).compareTo(new BigDecimal(0)) > 0) {
                                                                String msg = command.get(randomStartToEnd) + betPrice;
                                                                AdminWeixinUser adminWeixinUser = new AdminWeixinUser();
                                                                adminWeixinUser.setRoom(room);
                                                                adminWeixinUser.setWexinId(wexinId);
                                                                adminWeixinUser.setSendMsg(msg);
                                                                list1.add(adminWeixinUser);
                                                            } else {
                                                                //查看该机器人是否有待审核的上分记录
                                                                AdminUpdownBranch adminUpdownBranch = new AdminUpdownBranch();
                                                                adminUpdownBranch.setWexinId(wexinId);
                                                                adminUpdownBranch.setRoom(room);
                                                                adminUpdownBranch.setBranchType(1);
                                                                adminUpdownBranch.setAuditStatus(0);
                                                                AdminUpdownBranch updownBranchInfo = iAdminUpdownBranchService.selectAdminUpdownBranchByWeixinIdAndRoom(adminUpdownBranch);
                                                                if (updownBranchInfo == null) {
                                                                    Integer upPrice = compareFloatBetween2(new Float(minUpPriceValue), new Float(maxUpPriceValue));
                                                                    String msg = "上分" + upPrice;
                                                                    AdminWeixinUser adminWeixinUser = new AdminWeixinUser();
                                                                    adminWeixinUser.setRoom(room);
                                                                    adminWeixinUser.setWexinId(wexinId);
                                                                    adminWeixinUser.setSendMsg(msg);
                                                                    new Thread(new Runnable() {
                                                                        @Override
                                                                        public void run() {
                                                                            HttpUtils.sendPost(sendUrlTwo, "sendMsg=" + msg + "&room=" + room + "&wexinId=" + wexinId);
                                                                        }
                                                                    }).start();
                                                                }
                                                                break;
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }

                                    }
                                }
                            }

                            if (list.size() > 0) {
                                ArrayList<AdminWeixinUser> randomList = getRandomList(list);
                                for (AdminWeixinUser user : randomList) {
                                    Integer getSleepTime = getRandomStartToEnd(2000, 175000);
                                    String room = user.getRoom();
                                    String wexinId = user.getWexinId();
                                    String sendMsg = user.getSendMsg();
                                    String finalSendMsg = sendMsg;
                                    es3.submit(new Runnable() {
                                        @Override
                                        public void run() {
                                            try {
                                                Thread.sleep(getSleepTime);
                                            } catch (InterruptedException e) {
                                                e.printStackTrace();
                                            }
                                            HttpUtils.sendPost(sendUrlOne, "sendMsg=" + finalSendMsg + "&room=" + room + "&wexinId=" + wexinId);
                                        }
                                    });
                                }
                            }
                            if (list1.size() > 0) {
                                ArrayList<AdminWeixinUser> randomList = getRandomList(list1);
                                for (AdminWeixinUser user : randomList) {
                                    Integer getSleepTime = getRandomStartToEnd(2000, 175000);
                                    String room = user.getRoom();
                                    String wexinId = user.getWexinId();
                                    String sendMsg = user.getSendMsg();
                                    String finalSendMsg = sendMsg;
                                    es3.submit(new Runnable() {
                                        @Override
                                        public void run() {
                                            try {
                                                Thread.sleep(getSleepTime);
                                            } catch (InterruptedException e) {
                                                e.printStackTrace();
                                            }
                                            HttpUtils.sendPost(sendUrlTwo, "sendMsg=" + finalSendMsg + "&room=" + room + "&wexinId=" + wexinId);
                                        }
                                    });
                                }
                            }
                            AdminPrizeRecord updateRecord=new AdminPrizeRecord();
                            updateRecord.setIsRobot(1);
                            updateRecord.setRecordId(notPrizeRecord.getRecordId());
                            iAdminPrizeRecordService.updateAdminPrizeRecord(updateRecord);
                        }
                    }
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.toString());
        }
    }


    public void updateRootPrice(){
        logger.info("--------------更新微信机器人余额-----------------------");
        Long[] ids = iAdminWeixinUserService.selectAdminWeixinUserByRobotInfo();
        if (ids.length!=0) {
            iAdminWeixinUserService.updateAdminWeixinUserForRobot(ids);
        }

    }

    public static ArrayList<AdminWeixinUser> getRandomList(ArrayList<AdminWeixinUser> items) {
        // 存放乱序结果的集合
        ArrayList<AdminWeixinUser> result = new ArrayList<>();
        // 初始化随机数
        Random rand = new Random();
        // 取得集合的长度，for循环使用
        int size = items.size();
        // 遍历整个items数组
        for (int i = 0; i < size; i++) {
            // 任意取一个0~size的整数，注意此处的items.size()是变化的，所以不能用前面的size会发生数组越界的异常
            int myRand = rand.nextInt(items.size());
            //将取出的这个元素放到存放结果的集合中
            result.add(items.get(myRand));
            //从原始集合中删除该元素防止重复。注意，items数组大小发生了改变
            items.remove(myRand);
        }
        return result;
    }

    public void sendToStartToRoom(){
        AdminAgentInfo adminAgentInfo = new AdminAgentInfo();
        List<AdminAgentInfo> adminAgentInfos = iAdminAgentInfoService.selectAdminAgentInfoList(adminAgentInfo);
        String msg="开始下注！4分钟后封盘";
        if (adminAgentInfos.size() > 0) {
            for (int i = 0; i < adminAgentInfos.size(); i++) {
                if (adminAgentInfos.get(i).getAgentState()==1 && adminAgentInfos.get(i).getAgentType()==1) {
                    String room = adminAgentInfos.get(i).getRoom();
                    try {
                        String finalSendMsg = msg;
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                HttpUtils.sendPost(sendUrl, "sendMsg=" + finalSendMsg + "&room=" + room);
                            }
                        }).start();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public void sendImagesMessage(List<AdminPrizeRecord> notPrizeRecord){
        //查询所有代理
        AdminAgentInfo adminAgentInfo = new AdminAgentInfo();
        List<AdminAgentInfo> adminAgentInfos = iAdminAgentInfoService.selectAdminAgentInfoList(adminAgentInfo);
        if (adminAgentInfos.size() > 0) {

            List<List<List<String>>> allValue = new ArrayList<>();
            List<List<String>> allValue2 = new ArrayList<>();
            List<String> titles = new ArrayList<>();
            titles.add("标题可以识汉字不");
            List<List<String>> headers = new ArrayList<>();
            List<String> header = new ArrayList<>();
            header.add("开奖时间");//里面方法写死了头部，要改进去里面改
            header.add("期数");
            header.add("开奖号码");
            headers.add(header);
            for (AdminPrizeRecord record:notPrizeRecord) {
                List<String> allValue1 = new ArrayList<String>();
                allValue1.add(DateUtils.parseDateToStr("HH:mm", record.getPrizeTime()));
                allValue1.add(record.getPeriod().toString());
                allValue1.add(record.getLotteryNumber());
                allValue2.add(allValue1);
            }
            allValue.add(allValue2);
            String path = null;
            try {
                path = TestTable2.graphicsHtmlGeneration(allValue, titles, headers);
            } catch (Exception e) {
                e.printStackTrace();
            }

            for (int i = 0; i < adminAgentInfos.size(); i++) {
                if (adminAgentInfos.get(i).getAgentState()==1 && adminAgentInfos.get(i).getAgentType()==1) {
                    String room = adminAgentInfos.get(i).getRoom();
                    try {
                        logger.info("===生成开奖历史图片===");
                        String finalSendMsg = path;
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                HttpUtils.sendPost(sendUrl, "sendMsg=" + finalSendMsg + "&room=" + room + "&type=" + "img");
                            }
                        }).start();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
     }

    public void  sendAllMessageToRoom(AdminPrizeRecord notPrizeRecord){
        int[] normalArray = getNormalArray(notPrizeRecord.getLotteryNumber());
//            String sendMsg = "开奖期数：" + notPrizeRecord.getPeriod() + "\n";
        int[] position = getPosition(notPrizeRecord.getLotteryNumber());
//            sendMsg = sendMsg + "开奖号码：" + Arrays.toString(normalArray) + "\n";
        //查询所有代理
        AdminAgentInfo adminAgentInfo = new AdminAgentInfo();
        List<AdminAgentInfo> adminAgentInfos = iAdminAgentInfoService.selectAdminAgentInfoList(adminAgentInfo);
        if (adminAgentInfos.size() > 0) {
            for (int i = 0; i < adminAgentInfos.size(); i++) {
                if (adminAgentInfos.get(i).getAgentState()==1 && adminAgentInfos.get(i).getAgentType()==1) {
                    String sendMsg = "开奖期数：" + notPrizeRecord.getPeriod() + "\n";
                    sendMsg = sendMsg + "开奖号码：" + Arrays.toString(normalArray) + "\n";
                    sendMsg = sendMsg + "----------------------" + "\n";

                    String room = adminAgentInfos.get(i).getRoom();
                    BigDecimal odds = adminAgentInfos.get(i).getOdds();
                    Long id = adminAgentInfos.get(i).getId();
                    BigDecimal agentPrice = adminAgentInfos.get(i).getPrice();
                    AdminUserBetRecord adminUserBetRecord = new AdminUserBetRecord();
                    adminUserBetRecord.setRoom(room);
                    adminUserBetRecord.setPeriod(notPrizeRecord.getPeriod());
                    AdminUserBetRecord betRecordToAllPrice = new AdminUserBetRecord();
                    betRecordToAllPrice.setRoom(room);
                    betRecordToAllPrice.setPeriod(notPrizeRecord.getPeriod());
                    //该代理投注的所有金额
                    Double sumPrice = iAdminUserBetRecordService.selectAllSumPriceByPeriodAndRoom(betRecordToAllPrice);
                    if (sumPrice == null) {
                        //把没投注的玩家也展示出来
                        AdminWeixinUser roomUser = new AdminWeixinUser();
                        roomUser.setRoom(room);
                        List<AdminWeixinUser> adminWeixinUsers = iAdminWeixinUserService.selectAdminWeixinUserByRoom(roomUser);
                        for (AdminWeixinUser user : adminWeixinUsers) {
                            sendMsg = sendMsg + user.getWexinName() + "[" + user.getPrice() + "]：" + "\n";
                        }
                        String finalSendMsg = sendMsg;
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                HttpUtils.sendPost(sendUrl, "sendMsg=" + finalSendMsg + "&room=" + room);
                            }
                        }).start();
                        continue;
                    }
                    //抽水金额多位小数
                    Double moreV = sumPrice * new Double(odds.toString());
                    //代理抽水金额
                    Double v = new Double(String.format("%.2f", moreV));
                    //修改抽水几率
                    AdminPumpRecord adminPumpRecord = new AdminPumpRecord();
                    adminPumpRecord.setPrice(new BigDecimal(v));
                    adminPumpRecord.setPeriod(notPrizeRecord.getPeriod());
                    adminPumpRecord.setRoom(room);
                    iAdminPumpRecordService.updateAdminPumpRecordByPeriodAndRoom(adminPumpRecord);
                    //修改代理余额
                    AdminAgentInfo updateAgentInfo = new AdminAgentInfo();
                    updateAgentInfo.setId(id);
                    updateAgentInfo.setPrice(agentPrice.add(new BigDecimal(v)));
                    updateAgentInfo.setUpdateTime(DateUtils.getNowDate());
                    iAdminAgentInfoService.updateAdminAgentInfo(updateAgentInfo);
                    //剩余金额
                    Double remainPrice = sumPrice - sumPrice * new Double(odds.toString());
                    remainPrice = new Double(String.format("%.2f", remainPrice));
                    BigDecimal remainPriceTwo = new BigDecimal(sumPrice - sumPrice * new Double(odds.toString())).setScale(2, BigDecimal.ROUND_HALF_UP);
                    //统计每个球的下注列表
                    List<Map<String, List<AdminUserBetRecord>>> betList = new ArrayList<>();
                    //每个球对应的总金额
                    Map<String, Double> betPriceMap = new HashMap<>();
                    //记录那个球再分
                    int spiltNum = -1;
                    double spiltPrice = 0;
                    //用户统计金额
                    Map<String, BigDecimal> userPrice = new LinkedHashMap<>();

                    for (int j = 0; j < position.length; j++) {
                        Integer payNum = position[j];
                        adminUserBetRecord.setPayNum(payNum);
                        Double aDouble = iAdminUserBetRecordService.selectSumPriceByPeriodAndRoom(adminUserBetRecord);
                        if (aDouble != null && aDouble > 0) {
                            Map<String, List<AdminUserBetRecord>> betMap = new HashMap<>();
                            List<AdminUserBetRecord> userBetRecords = iAdminUserBetRecordService.selectAdminUserBetRecordByPeriodAndRoom(adminUserBetRecord);
                            betMap.put(payNum.toString(), userBetRecords);
                            betPriceMap.put(payNum.toString(), new Double(String.format("%.2f", aDouble)));
                            betList.add(betMap);
                        }
                    }
                    //特殊球之前
                    boolean flag = true;
                    //赔完钱之前
                    boolean afterFlag = true;
                    //不够赔（赔完后不可逆）
                    boolean isFlg = true;
                    for (Map<String, List<AdminUserBetRecord>> betInfo : betList) {
                        for (String key : betInfo.keySet()) {//keySet获取map集合key的集合  然后在遍历key即可
                            if (remainPriceTwo.compareTo(new BigDecimal(0)) == -1) {
                                flag = false;
                            }
                            BigDecimal bigDecimal = new BigDecimal(betPriceMap.get(key) * 2);
                            remainPriceTwo = remainPriceTwo.subtract(new BigDecimal(bigDecimal.toString())).setScale(2, BigDecimal.ROUND_HALF_UP);
                            List<AdminUserBetRecord> betRecordArrayList = betInfo.get(key);
                            BigDecimal littlePrice = new BigDecimal(0);
                            if (remainPriceTwo.compareTo(new BigDecimal(0)) < 0) {
                                littlePrice = remainPriceTwo.add(new BigDecimal(betPriceMap.get(key)));
                            }
                            if (littlePrice.compareTo(new BigDecimal(0)) >= 0) {
                                //大于单倍
                                isFlg = true;
                            } else {
                                //小于单倍
                                isFlg = false;
                            }
                            BigDecimal littlePriceOne = new BigDecimal(0);
                            for (AdminUserBetRecord betRecordArrayInfo : betRecordArrayList) {

                                if (remainPriceTwo.compareTo(new BigDecimal(0)) >= 0 && flag) {
                                    //够赔
                                    if (userPrice.get(betRecordArrayInfo.getWexinId()) == null) {
                                        userPrice.put(betRecordArrayInfo.getWexinId(), betRecordArrayInfo.getPayPrice());
                                    } else {
                                        userPrice.put(betRecordArrayInfo.getWexinId(), userPrice.get(betRecordArrayInfo.getWexinId()).add(betRecordArrayInfo.getPayPrice()).setScale(2, BigDecimal.ROUND_HALF_UP));
                                    }
                                } else if (remainPriceTwo.compareTo(new BigDecimal(0)) == -1 && flag) {

                                    //首次进入
                                    if (betRecordArrayInfo.getId() == betRecordArrayList.get(0).getId()) {
                                        littlePriceOne = littlePrice;
                                    }
                                    //不够赔
                                    //大于单倍
                                    if (isFlg) {
                                        //剩余留下的金额
                                        littlePriceOne = littlePriceOne.subtract(betRecordArrayInfo.getPayPrice()).setScale(2, BigDecimal.ROUND_HALF_UP);
                                        if (littlePriceOne.compareTo(new BigDecimal(0)) >= 0) {
                                            if (userPrice.get(betRecordArrayInfo.getWexinId()) == null) {
                                                userPrice.put(betRecordArrayInfo.getWexinId(), new BigDecimal(betRecordArrayInfo.getPayPrice().toString()).setScale(2, BigDecimal.ROUND_HALF_UP));
                                            } else {
                                                userPrice.put(betRecordArrayInfo.getWexinId(), userPrice.get(betRecordArrayInfo.getWexinId()).add(new BigDecimal(betRecordArrayInfo.getPayPrice().toString())).setScale(2, BigDecimal.ROUND_HALF_UP));
                                            }
                                        } else if (littlePriceOne.compareTo(new BigDecimal(0)) < 0) {
                                            if (littlePriceOne.add(betRecordArrayInfo.getPayPrice()).compareTo(new BigDecimal(0)) > 0 && afterFlag) {
                                                if (userPrice.get(betRecordArrayInfo.getWexinId()) == null) {
                                                    userPrice.put(betRecordArrayInfo.getWexinId(), littlePriceOne.add(betRecordArrayInfo.getPayPrice()).setScale(2, BigDecimal.ROUND_HALF_UP));
                                                } else {
                                                    userPrice.put(betRecordArrayInfo.getWexinId(), userPrice.get(betRecordArrayInfo.getWexinId()).add(littlePriceOne.add(betRecordArrayInfo.getPayPrice())).setScale(2, BigDecimal.ROUND_HALF_UP));
                                                }
                                                afterFlag = false;
                                            } else {
                                                if (userPrice.get(betRecordArrayInfo.getWexinId()) == null) {
                                                    userPrice.put(betRecordArrayInfo.getWexinId(), new BigDecimal(0));
                                                } else {
                                                    userPrice.put(betRecordArrayInfo.getWexinId(), userPrice.get(betRecordArrayInfo.getWexinId()).add(new BigDecimal(0)).setScale(2, BigDecimal.ROUND_HALF_UP));
                                                }
                                            }
                                        }
                                    }
                                    //小于单倍
                                    if (!isFlg) {
                                        //剩余下来的金额
                                        littlePriceOne = littlePriceOne.add(betRecordArrayInfo.getPayPrice()).setScale(2, BigDecimal.ROUND_HALF_UP);
                                        if (littlePriceOne.compareTo(new BigDecimal(0)) <= 0) {
                                            if (userPrice.get(betRecordArrayInfo.getWexinId()) == null) {
                                                userPrice.put(betRecordArrayInfo.getWexinId(), betRecordArrayInfo.getPayPrice().negate().setScale(2, BigDecimal.ROUND_HALF_UP));
                                            } else {
                                                userPrice.put(betRecordArrayInfo.getWexinId(), userPrice.get(betRecordArrayInfo.getWexinId()).subtract(betRecordArrayInfo.getPayPrice()).setScale(2, BigDecimal.ROUND_HALF_UP));
                                            }
                                        } else if (littlePriceOne.compareTo(new BigDecimal(0)) > 0) {
                                            if (littlePriceOne.subtract(betRecordArrayInfo.getPayPrice()).compareTo(new BigDecimal(0)) < 0 && afterFlag) {
                                                if (userPrice.get(betRecordArrayInfo.getWexinId()) == null) {
                                                    userPrice.put(betRecordArrayInfo.getWexinId(), littlePriceOne.subtract(betRecordArrayInfo.getPayPrice()).setScale(2, BigDecimal.ROUND_HALF_UP));
                                                } else {
                                                    userPrice.put(betRecordArrayInfo.getWexinId(), userPrice.get(betRecordArrayInfo.getWexinId()).add(littlePriceOne.subtract(betRecordArrayInfo.getPayPrice())).setScale(2, BigDecimal.ROUND_HALF_UP));
                                                }
                                                afterFlag = false;
                                            } else {
                                                if (userPrice.get(betRecordArrayInfo.getWexinId()) == null) {
                                                    userPrice.put(betRecordArrayInfo.getWexinId(), new BigDecimal(0).setScale(2, BigDecimal.ROUND_HALF_UP));
                                                } else {
                                                    userPrice.put(betRecordArrayInfo.getWexinId(), userPrice.get(betRecordArrayInfo.getWexinId()).add(new BigDecimal(0))).setScale(2, BigDecimal.ROUND_HALF_UP);
                                                }
                                            }
                                        }
                                    }

                                } else if (!flag) {
                                    if (userPrice.get(betRecordArrayInfo.getWexinId()) == null) {
                                        userPrice.put(betRecordArrayInfo.getWexinId(), betRecordArrayInfo.getPayPrice().negate().setScale(2, BigDecimal.ROUND_HALF_UP));
                                    } else {
                                        userPrice.put(betRecordArrayInfo.getWexinId(), userPrice.get(betRecordArrayInfo.getWexinId()).subtract(betRecordArrayInfo.getPayPrice()).setScale(2, BigDecimal.ROUND_HALF_UP));
                                    }
                                }
                            }
                        }
                    }
                    String sendMsg2 = "";
                    ArrayList<WeChatUser> persons = new ArrayList<WeChatUser>();
                    //遍历用户盈利标志
                    for (String key : userPrice.keySet()) {
                        //统计用户在这期投了多少钱
                        AdminUserBetRecord userBetRecord = new AdminUserBetRecord();
                        userBetRecord.setRoom(room);
                        userBetRecord.setPeriod(notPrizeRecord.getPeriod());
                        userBetRecord.setWexinId(key);
                        Double aDouble = iAdminUserBetRecordService.selectSumPriceByPeriodAndRoomAndWexinId(userBetRecord);
                        //记录用户赢了或者亏了多少钱
                        Double earnPrice = aDouble + new Double(userPrice.get(key).toString());

                        //开奖返回金额
                        AdminWeixinUser weixinUser1 = new AdminWeixinUser();
                        weixinUser1.setWexinId(key);
                        weixinUser1.setRoom(room);
                        AdminWeixinUser weixinUser2 = iAdminWeixinUserService.selectAdminWeixinUserByWeChatIdAndRoom(weixinUser1);
                        AdminWeixinUser updateWeixinUser = new AdminWeixinUser();
                        updateWeixinUser.setId(weixinUser2.getId());
                        updateWeixinUser.setPrice(weixinUser2.getPrice().add(new BigDecimal(earnPrice)));
                        updateWeixinUser.setUpdateTime(DateUtils.getNowDate());
                        iAdminWeixinUserService.updateAdminWeixinUser(updateWeixinUser);


                        //查询用户最新金额
                        AdminWeixinUser adminWeixinUser1 = new AdminWeixinUser();
                        adminWeixinUser1.setWexinId(key);
                        adminWeixinUser1.setRoom(room);
                        AdminWeixinUser adminWeixinUser = iAdminWeixinUserService.selectAdminWeixinUserByWeChatIdAndRoom(adminWeixinUser1);

                        //记录用户流水
                        AdminUserFlowing adminUserFlowing = new AdminUserFlowing();
                        adminUserFlowing.setUpdateTime(DateUtils.getNowDate());
                        adminUserFlowing.setStartPrice(weixinUser2.getPrice());
                        adminUserFlowing.setPayPrice(new BigDecimal(earnPrice));
                        adminUserFlowing.setEndPrice(adminWeixinUser.getPrice());
                        adminUserFlowing.setUserId(adminWeixinUser.getId());
                        adminUserFlowing.setWexinId(adminWeixinUser.getWexinId());
                        adminUserFlowing.setWexinName(adminWeixinUser.getWexinName());
                        adminUserFlowing.setIsFlowing(1);
                        adminUserFlowing.setPayType(2);
                        adminUserFlowing.setRoom(room);
                        adminUserFlowing.setRemark("开奖返回金额");
                        adminUserFlowing.setPeriod(notPrizeRecord.getPeriod().intValue());
                        iAdminUserFlowingService.insertAdminUserFlowing(adminUserFlowing);

                        String str = userPrice.get(key).compareTo(new BigDecimal(0)) > -1 ? "%2B" : "";
//                    sendMsg = sendMsg + adminWeixinUser.getWexinName() + "[" + adminWeixinUser.getPrice() + "]：(" + str + userPrice.get(key).toString() + ")\n";
                        sendMsg2 = sendMsg2 + adminWeixinUser.getWexinName() + " " + str + userPrice.get(key).toString() + "\n";
                        WeChatUser weChatUser = new WeChatUser();
                        weChatUser.setOldPrice(adminWeixinUser.getPrice());
                        weChatUser.setWexinName(adminWeixinUser.getWexinName());
                        weChatUser.setPrice(userPrice.get(key));
                        persons.add(weChatUser);
                    }

                    //把没投注的玩家也展示出来
                    AdminWeixinUser roomUser = new AdminWeixinUser();
                    roomUser.setRoom(room);
                    List<AdminWeixinUser> adminWeixinUsers = iAdminWeixinUserService.selectAdminWeixinUserByRoom(roomUser);
                    for (AdminWeixinUser user : adminWeixinUsers) {
                        if (userPrice.get(user.getWexinId()) == null) {
                            WeChatUser weChatUser = new WeChatUser();
                            weChatUser.setOldPrice(user.getPrice());
                            weChatUser.setWexinName(user.getWexinName());
                            weChatUser.setPrice(new BigDecimal(0));
                            persons.add(weChatUser);
//                        sendMsg = sendMsg + user.getWexinName() + "[" + user.getPrice() +"]："+"\n";
                        }
                    }
                    Collections.sort(persons, new Comparator<WeChatUser>() {
                        @Override
                        public int compare(WeChatUser o1, WeChatUser o2) {
                            return o2.getOldPrice().compareTo(o1.getOldPrice()) > 0 ? 1 : -1;
                        }
                    });
                    for (WeChatUser chatUser : persons) {
                        if (chatUser.getPrice().compareTo(new BigDecimal(0)) != 0) {
                            String str = chatUser.getPrice().compareTo(new BigDecimal(0)) > -1 ? "%2B" : "";
                            sendMsg = sendMsg + chatUser.getWexinName() + "[" + chatUser.getOldPrice().toString() + "]：(" + str + chatUser.getPrice().toString() + ")\n";
                        } else {
                            sendMsg = sendMsg + chatUser.getWexinName() + "[" + chatUser.getOldPrice() + "]：" + "\n";
                        }
                    }
                    String finalSendMsg = sendMsg;
                    String finalSendMsg2 = sendMsg2;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            HttpUtils.sendPost(sendUrl, "sendMsg=" + finalSendMsg + "&room=" + room);
                            HttpUtils.sendPost(sendUrl, "sendMsg=" + finalSendMsg2 + "&room=" + room);
                        }
                    }).start();
                }
            }
        }
    }

    public String getRandomNum() {
        HashSet<String> hs = new HashSet<>();
        //2、使用Random类随机产生10个1~20的整数
        Random r = new Random();
        while (hs.size() < 8) {
            Integer i = r.nextInt(20) + 1;
            if (i < 10) {
                hs.add("0" + i);
            } else {
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             hs.add(i.toString());
            }

        }
        List list = new ArrayList(hs);
        Collections.shuffle(list);//再打乱一次顺序
        String join = StringUtils.join(list, ",");
//        String join = StringUtils.join(hs, ",");
        return join;
    }

    public int[] getArray(String lotteryNumber){
        String[] split = lotteryNumber.split(",");
        int[] array = new int[split.length];
        for (int i = 0; i < split.length; i++) {
            array[i] = Integer.valueOf(split[i]).intValue();
        }
        int temp;
        for (int i = 0; i < array.length; i++) {
            for (int j = i + 1; j < array.length; j++) {
                if (array[i] < array[j]) {
                    temp = array[i];
                    array[i] = array[j];
                    array[j] = temp; // 两个数交换位置
                }
            }
        }
        return array;
    }

    public int[] getNormalArray(String lotteryNumber){
        String[] split = lotteryNumber.split(",");
        int[] array = new int[split.length];
        for (int i = 0; i < split.length; i++) {
            array[i] = Integer.valueOf(split[i]).intValue();
        }
        return array;
    }

    public int[] getPosition (String lotteryNumber){
        String[] split = lotteryNumber.split(",");
        int[] array = new int[split.length];
        int[] startArray = new int[split.length];
        int[] returnArray = new int[split.length];
        for (int i = 0; i < split.length; i++) {
            array[i] = Integer.valueOf(split[i]).intValue();
            startArray[i] = Integer.valueOf(split[i]).intValue();
        }
        int temp;
        for (int i = 0; i < array.length; i++) {
            for (int j = i + 1; j < array.length; j++) {
                if (array[i] < array[j]) {
                    temp = array[i];
                    array[i] = array[j];
                    array[j] = temp; // 两个数交换位置
                }
            }
        }
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < startArray.length; j++) {
                if (startArray[j] == array[i]) {
                    returnArray[i] = j + 1;
                }
            }
        }
        return returnArray;
    }

    private static int getRandomStartToEnd(int x, int y) {
        int num = -1;
        //说明：两个数在合法范围内，并不限制输入的数哪个更大一些
        if (x < 0 || y < 0) {
            return num;
        } else {
            int max = Math.max(x, y);
            int min = Math.min(x, y);
            int mid = max - min;//求差
            //产生随机数
            num = (int) (Math.random() * (mid + 1)) + min;
        }
        return num;
    }

    public static Integer mockFloatBetween2(Float begin, Float end,BigDecimal price) {
        if (new BigDecimal(begin).compareTo(price)<0) {
            BigDecimal bigDecimal = new BigDecimal(end - begin);
            BigDecimal point = new BigDecimal(Math.random());
            BigDecimal pointBetween = point.multiply(bigDecimal);
            BigDecimal result = pointBetween.add(new BigDecimal(begin)).setScale(2, BigDecimal.ROUND_FLOOR);
            int intValue = result.intValue();
            int i1 = LengthNum(intValue);
            int endNum = getEndNum(i1, intValue);
            return endNum;
        }else{
            return 0;
        }
    }

    public static Integer compareFloatBetween2(Float begin, Float end) {
        BigDecimal bigDecimal = new BigDecimal(end - begin);
        BigDecimal point = new BigDecimal(Math.random());
        BigDecimal pointBetween = point.multiply(bigDecimal);
        BigDecimal result = pointBetween.add(new BigDecimal(begin)).setScale(2, BigDecimal.ROUND_FLOOR);
        int intValue = result.intValue();
        int i1 = LengthNum(intValue);
        int endNum = getEndNum(i1, intValue);
        return endNum;
    }
//
    public static void main(String[] args) {

//        BigDecimal bigDecimal = new BigDecimal(20000 -100 );
//        for (int i=0;i<100;i++) {
//            BigDecimal point = new BigDecimal(Math.random());
//            BigDecimal pointBetween = point.multiply(bigDecimal);
//            BigDecimal result = pointBetween.add(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_FLOOR);
//            int intValue = result.intValue();
//            int i1 = LengthNum(intValue);
//            int endNum = getEndNum(i1, intValue);
//            System.out.println(endNum);
//        }
//        boolean dd=new BigDecimal("3781.70").compareTo(new BigDecimal("3781.7"))>=0;
//        System.out.println(dd);
        List<AdminWeixinUser> adminWeixinUsers=new ArrayList<>();
        for (Integer i=0;i<100;i++) {
            AdminWeixinUser adminWeixinUser = new AdminWeixinUser();
            adminWeixinUser.setWexinId(i.toString());
            adminWeixinUser.setWexinName("狗");
            adminWeixinUser.setRoom("room"+i.toString());
            adminWeixinUser.setSendMsg("屌你老母亲"+i);
            adminWeixinUsers.add(adminWeixinUser);
        }
        int result=0;
        ExecutorService es3 = Executors.newCachedThreadPool();
        for (AdminWeixinUser user : adminWeixinUsers) {
            Integer getSleepTime = getRandomStartToEnd(2000, 180000);
            result=result+getSleepTime;
            final int result1=result;
            System.out.println(getSleepTime);
            String room = user.getRoom();
            String wexinId = user.getWexinId();
            String sendMsg = user.getSendMsg();
            String finalSendMsg = sendMsg;
            //创建线程词

            es3.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(getSleepTime);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    HttpUtils.sendPost("http://192.168.0.136:8099/api/test", "sendMsg=" + finalSendMsg + "&room=" + room + "&wexinId=" + wexinId);
                }
            });
        }
    }

    public static int LengthNum(int num) {
        int count=0; //计数
        while(num>=1) {
            num/=10;
            count++;
        }
        return count;
    }

    public static int getEndNum(int count,int num) {
        int ride=1;
        for (int i=0;i<count-1;i++) {
            ride=ride*10;
        }
        num=num/ride;
        num=num*ride;
        return num;
    }

//
}
